import React, { useEffect } from "react";
import { Toast } from "react-vant";
let point;
let map;
let marker;
const MyMap = () => {
  useEffect(() => {
    map = new window.BMapGL.Map("container"); // 创建地图实例
    point = new window.BMapGL.Point(116.404, 39.915);
    console.log(point, "初始化——point");
    map.centerAndZoom(point, 15); // 初始化地图，设置中心点坐标和地图级别
    map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
    // 开启定位之前，加载提示，提升用户体验，
    Toast.loading({
      message: "定位中...",
      duration: 10000,
    });
    // 开启定位;
    const geolocation = new window.BMapGL.Geolocation();
    // 获取当前位置;
    geolocation.getCurrentPosition(function (result) {
      Toast.clear(); //定位成功后，关闭提示
      console.log(result, "获取当前位置-----result");
      // 如果能定位到经度，则定位成功
      if (result && result.point.lng) {
        console.log("当前位置：" + result.point.lng + "," + result.point.lat);
        point.lng = result.point.lng;
        point.lat = result.point.lat;
        console.log(point, "定位后——point");
        map.centerAndZoom(point, 15); // 更改中心点坐标
        marker = new window.BMapGL.Marker(point); // 创建标注
        map.addOverlay(marker); // 将标注添加到地图中
      } else {
        Toast("定位失败");
      }
      map.addEventListener("click", function (e) {
        point.lng = e.latlng.lng;
        point.lat = e.latlng.lat;
        console.log(point, "选点后——point");
        map.centerAndZoom(point, 15); // 更改中心点坐标
        marker = new window.BMapGL.Marker(point); // 创建标注
        map.addOverlay(marker); // 将标注添加到地图中
      });
    });
    // useEffect返回一个函数时，模拟componentsWillUnmount 执行组件销毁前的代码
    return () => {
      Toast.clear();
    };
  }, []);

  return <div id="container" style={{ width: "100%", height: "100%" }}></div>;
};

export default MyMap;
